﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace Chaotic.Core.Extension
{
    public static class ExcelExtension
    {
        public static string ExcelHeader()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("<?xml version=\"1.0\"?>\n");
            stringBuilder.Append("<?mso-application progid=\"Excel.Sheet\"?>\n");
            stringBuilder.Append("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" ");
            stringBuilder.Append("xmlns:o=\"urn:schemas-microsoft-com:office:office\" ");
            stringBuilder.Append("xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ");
            stringBuilder.Append("xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" ");
            stringBuilder.Append("xmlns:html=\"http://www.w3.org/TR/REC-html40\">\n");
            stringBuilder.Append("<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
            stringBuilder.Append("</DocumentProperties>");
            stringBuilder.Append("<ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">\n");
            stringBuilder.Append("<ProtectStructure>False</ProtectStructure>\n");
            stringBuilder.Append("<ProtectWindows>False</ProtectWindows>\n");
            stringBuilder.Append("</ExcelWorkbook>\n");
            return stringBuilder.ToString();
        }

        public static void ExportToExcel(DataSet source, string fileName, string[] filterColumn)
        {
            StreamWriter streamWriter = new StreamWriter(fileName);
            string text = ExcelHeader();
            text += "<Styles>\r\n <Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n <Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>\r\n <Protection/>\r\n </Style>\r\n <Style ss:ID=\"BoldColumn\">\r\n <Font x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n <Style ss:ID=\"StringLiteral\">\r\n <NumberFormat ss:Format=\"@\"/>\r\n </Style>\r\n <Style ss:ID=\"Decimal\">\r\n <NumberFormat ss:Format=\"0.0000\"/>\r\n </Style>\r\n <Style ss:ID=\"Integer\">\r\n <NumberFormat ss:Format=\"0\"/>\r\n </Style>\r\n <Style ss:ID=\"DateLiteral\">\r\n <NumberFormat ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n </Styles>\r\n ";
            int num = 0;
            int num2 = 1;
            streamWriter.Write(text);
            streamWriter.Write("<Worksheet ss:Name=\"Sheet" + num2 + "\">");
            streamWriter.Write("<Table>");
            streamWriter.Write("<Row>");
            for (int i = 0; i < source.Tables[0].Columns.Count; i++)
            {
                string columnName = source.Tables[0].Columns[i].ColumnName;
                if (filterColumn == null || !filterColumn.Contains(columnName))
                {
                    streamWriter.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
                    streamWriter.Write(columnName);
                    streamWriter.Write("</Data></Cell>");
                }
            }

            streamWriter.Write("</Row>");
            foreach (DataRow row in source.Tables[0].Rows)
            {
                num++;
                if (num == 64000)
                {
                    num = 0;
                    num2++;
                    streamWriter.Write("</Table>");
                    streamWriter.Write(" </Worksheet>");
                    streamWriter.Write("<Worksheet ss:Name=\"Sheet" + num2 + "\">");
                    streamWriter.Write("<Table>");
                }

                streamWriter.Write("<Row>");
                for (int j = 0; j < source.Tables[0].Columns.Count; j++)
                {
                    string columnName2 = source.Tables[0].Columns[j].ColumnName;
                    if (filterColumn != null && filterColumn.Contains(columnName2))
                    {
                        continue;
                    }

                    Type type = row[j].GetType();
                    switch (type.ToString())
                    {
                        case "System.String":
                            {
                                string text2 = row[j].ToString();
                                text2 = text2.Trim();
                                text2 = SecurityElement.Escape(text2);
                                streamWriter.Write("<Cell ss:StyleID=\"StringLiteral\"><Data ss:Type=\"String\">");
                                streamWriter.Write(text2);
                                streamWriter.Write("</Data></Cell>");
                                break;
                            }
                        case "System.DateTime":
                            {
                                DateTime dateTime = (DateTime)row[j];
                                string value = "";
                                if (dateTime != DateTime.MinValue)
                                {
                                    value = dateTime.Year.ToString(CultureInfo.InvariantCulture) + "-" + ((dateTime.Month < 10) ? ("0" + dateTime.Month.ToString(CultureInfo.InvariantCulture)) : dateTime.Month.ToString(CultureInfo.InvariantCulture)) + "-" + ((dateTime.Day < 10) ? ("0" + dateTime.Day.ToString(CultureInfo.InvariantCulture)) : dateTime.Day.ToString(CultureInfo.InvariantCulture)) + "T" + ((dateTime.Hour < 10) ? ("0" + dateTime.Hour.ToString(CultureInfo.InvariantCulture)) : dateTime.Hour.ToString(CultureInfo.InvariantCulture)) + ":" + ((dateTime.Minute < 10) ? ("0" + dateTime.Minute.ToString(CultureInfo.InvariantCulture)) : dateTime.Minute.ToString(CultureInfo.InvariantCulture)) + ":" + ((dateTime.Second < 10) ? ("0" + dateTime.Second.ToString(CultureInfo.InvariantCulture)) : dateTime.Second.ToString(CultureInfo.InvariantCulture)) + ".000";
                                }

                                streamWriter.Write("<Cell ss:StyleID=\"DateLiteral\"><Data ss:Type=\"DateTime\">");
                                streamWriter.Write(value);
                                streamWriter.Write("</Data></Cell>");
                                break;
                            }
                        case "System.Boolean":
                            streamWriter.Write("<Cell ss:StyleID=\"StringLiteral\"><Data ss:Type=\"String\">");
                            streamWriter.Write(row[j].ToString());
                            streamWriter.Write("</Data></Cell>");
                            break;
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            streamWriter.Write("<Cell ss:StyleID=\"Integer\"><Data ss:Type=\"Number\">");
                            streamWriter.Write(row[j].ToString());
                            streamWriter.Write("</Data></Cell>");
                            break;
                        case "System.Decimal":
                        case "System.Double":
                            streamWriter.Write("<Cell ss:StyleID=\"Decimal\"><Data ss:Type=\"Number\">");
                            streamWriter.Write(row[j].ToString());
                            streamWriter.Write("</Data></Cell>");
                            break;
                        case "System.DBNull":
                            streamWriter.Write("<Cell ss:StyleID=\"StringLiteral\"><Data ss:Type=\"String\">");
                            streamWriter.Write("");
                            streamWriter.Write("</Data></Cell>");
                            break;
                        default:
                            throw new Exception(string.Concat(type, " not handled."));
                    }
                }

                streamWriter.Write("</Row>");
            }

            streamWriter.Write("</Table>");
            streamWriter.Write(" </Worksheet>");
            streamWriter.Write("</Workbook>");
            streamWriter.Close();
        }
    }
}
